import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'

Vue.use(VueRouter)
const whiteRoute = ['/login', '/reg']

const routes = [
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login/loginPage.vue')
  },
  {
    path: '/register',
    name: 'register',
    component: () => import('@/views/register/registerPage.vue')
  },
  {
    path: '/',
    component: () => import('@/views/layout/layoutPage.vue'),
    children: [
      {
        path: '/home',
        name: 'home',
        component: () => import('@/views/layout/homeCom.vue')
      },
      {
        path: '/user-info',
        name: 'user-info',
        component: () => import('@/views/layout/userInfoCom.vue')
      },
      {
        path: 'user-avatar',
        name: 'user-avatar',
        component: () => import('@/views/layout/userImgCom.vue')
      },
      {
        path: 'user-pwd',
        name: 'user-pwd',
        component: () => import('@/views/layout/userPwdCom.vue')
      },
      {
        path: 'art-cate',
        name: 'art-cate',
        component: () => import('@/views/layout/artCateCom.vue')
      },
      {
        path: 'art-list',
        name: 'art-list',
        component: () => import('@/views/layout/artListCom.vue')
      },
      {
        path: 'art-draft',
        name: 'art-draft',
        component: () => import('@/views/layout/artListCom.vue')
      }
    ]
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {
  const token = store.state.token
  if (token) {
    if (token && !store.state.userInfo.username) {
      store.dispatch('getUserInfoAction')
    }
  } else {
    if (whiteRoute.includes(to.path)) next()
    else next('/login')
  }
  next()
})

export default router
